package org.cc.media.player;

import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.apache.commons.io.IOUtils;

public class ShoutcastStreamPlayer implements Runnable {
	
	private static final Integer BUFFER_SIZE = 32768;
	
	public ShoutcastStreamPlayer(InputStream stream) {
		this.inStream = stream;
	}
	
	private InputStream inStream;
	private AudioInputStream audioStream;
	private SourceDataLine audioLine;
	private Boolean playStream = true;
	
	@Override
	public void run() {
		try {
			audioStream = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, AudioSystem.getAudioInputStream(inStream));
			AudioFormat format = audioStream.getFormat();
			DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
			audioLine = (SourceDataLine) AudioSystem.getLine(info);
			audioLine.open(format);
			audioLine.start();
			while (playStream) {
				play();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(inStream);
			IOUtils.closeQuietly(audioStream);
		}
	}
	
	private void play() throws IOException {
		byte[] bytesBuffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = audioStream.read(bytesBuffer)) != -1 && playStream) {
			audioLine.write(bytesBuffer, 0, bytesRead);
		}
	}
	
	public Boolean getPlayStream() {
		return playStream;
	}

	public void setPlayStream(Boolean playStream) {
		this.playStream = playStream;
	}

}
